<script setup>
import { ref, reactive, onMounted, watch, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fileApi } from '@T2/service/api.ts';
import { api } from '@T2/plugins/env-config.ts';
import { downloadFiles2 } from '@T2/utils/utils.ts';

const { config } = defineProps({
  config: {
    type: Object,
    required: true,
  }
});
const emits = defineEmits(['change']);

const Rt = reactive({
  filelist: (config.value || []).map(i => {
    return { oldURL: i.url, url: api + i.url, name: i.name }
  }),
  canShowRemoveDialog: true,/* 删除弹窗标志，上传不符合格式的文件会触发beforeRemove，此时不弹窗 */
});
const handleBeforeUpload = (file) => {
  const isLtMaxSize = file.size / 1024 / 1024 < config.maxMB; // 检查文件大小是否小于maxMB
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过 ${config.maxMB}MB！`);
    Rt.canShowRemoveDialog = false; // 禁止显示删除弹窗
    return false;
  }
  return true; // 返回 true 表示允许上传，返回 false 表示禁止上传
}
const handleFileUpload = (option) => {
  let formData = new FormData();
  formData.append('file', option.file);
  formData.append('ftype', '表单附件');
  formData.append('name', option.file.name);
  fileApi({
    method: 'post',
    data: formData,
  }).then(res => {
    option.onSuccess(res, option.file);
  }).catch(error => {
    option.onError(error);
  });
}
const handleSuccess = (response, file, fileList) => {
  const data = fileList.map(i => {
    return { url: i.response?.file_url || i.oldURL, name: i.response?.name || i.name };
  });
  emits('change', data);
}

const beforeRemove = (uploadFile, uploadFiles) => {
  if (Rt.canShowRemoveDialog) {
    return ElMessageBox.confirm('', {
      message: h('div', null, [
        h('p', { style: 'font-size:16px;color: #4C4C4C;font-weight:500;' }, `移除附件 ${uploadFile.name} ?`),
        h('p', { style: 'font-size:14px;color: #9D9D9D;margin:10px 0;' }, '确认后不会立即移除，需再次确认弹窗才会移除。'),
      ]),
      type: 'warning',
      confirmButtonText: '确认',
    }).then(
      () => true,
      () => false
    )
  } else {
    Rt.canShowRemoveDialog = true;/* 重置状态 */
    return true;
  }
}
const handleRemove = (file, uploadFiles) => {
  const data = uploadFiles.map(i => {
    return { url: i.response?.file_url || i.oldURL, name: i.response?.name || i.name };
  });
  emits('change', data);
}

const download = (file) => {
  console.log(file);
  ElMessageBox.confirm('', {
    message: h('div', null, [
      h('p', { style: 'font-size:16px;color: #4C4C4C;font-weight:500;' }, `是否下载文件 ${file.name} ?`)
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
      downloadFiles2(file.name, file.url);
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
</script>

<template>
  <div class="box box-flex--center" v-if="config.edit">
    <el-upload class="upload-demo flex--center" v-model:file-list="Rt.filelist" :limit="config.limit"
      :disabled="Rt.filelist.length >= config.limit" multiple :before-upload="handleBeforeUpload"
      :http-request="handleFileUpload" :on-success="handleSuccess" :before-remove="beforeRemove"
      :on-remove="handleRemove">
      <el-button type="primary" :disabled="Rt.filelist.length >= config.limit">
        上传附件
      </el-button>
    </el-upload>
    <div class="box-download" @click="download(Rt.filelist[0])">下载</div>
  </div>
  <div class="box" v-else>
    <el-upload class="upload-demo" v-model:file-list="Rt.filelist" :limit="config.limit"
      :disabled="Rt.filelist.length >= config.limit" multiple :before-upload="handleBeforeUpload"
      :http-request="handleFileUpload" :on-success="handleSuccess" :before-remove="beforeRemove"
      :on-remove="handleRemove">
      <el-button type="primary" :disabled="Rt.filelist.length >= config.limit">
        上传附件
      </el-button>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.box-flex--center {
  display: flex !important;
  align-items: center;
  width: 100%;

}

.upload-demo {
  width: 40%;
}

.box-download {
  padding: 0 20px;
}

:deep(.el-upload-list) {
  width: 100%;
  min-width: 200px;
}
</style>